import React, { Component } from 'react';
import { high, base, ajax, getMultiLang } from 'nc-lightapp-front';
const { NCButton: Button, NCTable: Table, NCCheckbox: Checkbox, NCModal: Modal } = base;
import drawinAss from './methods/index';
import { commonApi } from '../../../common/actions';

const modalStyle = { minHeight: '268px', maxHeight: '470px' }
const defaultProps12 = {
    prefixCls: "bee-table",
    multiSelect: {
        type: "checkbox",
        param: "key"
    }
};
export default class AssModal extends Component {
    constructor(props) {
        super(props);
        this.state = {
            json: {},
            showModal: false,
            isShowUnit: false,//是否显示业务单元
            assData: [//辅助核算信息
            ],
            childAssData: [],//接受父组件传过来的参数
            loadData: [],//查询模板加载数据
            listItem: {},//模板数据对应值
            checkedAll: true,//默认全选中
            SelectedAssData: [],//选中的数据
            checkedArray: [],
            assidData: {}, //key=assid,value=assData
            assitemData: {} //key=pk_accasoa+prepareddate,value=assitems
        };
        this.close = this.close.bind(this);
    }
    componentWillMount() {
        let callback = (json) => {
            this.setState({
                json: json
            }, () => {
            })
        }
        getMultiLang({ moduleId: 'publiccomponents', domainName: 'gl', currentLocale: 'simpchn', callback });
    }
    componentWillReceiveProps(nextProp) {
        /** 
            *父组件传递过来的pretentAssData里包含 
            *   pk_accountingbook,
            *   pk_accasoa,
            *   prepareddate,
            *   pk_org,
            *   assData,
            *   assid,
            *   checkboxShow,是否显示复选框 true、false
            *   checkedAll 是否全选中 true， false
            *   pk_defdoclist,
            */
        let self = this;
        let { checkedAll, assData, checkedArray, childAssData } = self.state;
        let { pretentAssData } = nextProp;
        if (nextProp.showOrHide && childAssData != pretentAssData) {
            childAssData = pretentAssData;
            if (typeof pretentAssData.checkedAll === 'boolean') {//接收父组件传递过来的checkedAll
                checkedAll = pretentAssData.checkedAll;
            } else {
                checkedAll = true;
            }
            if (pretentAssData.assData && pretentAssData.assData.length > 0) {
                checkedArray = [];
                pretentAssData.assData.map((item, index) => {
                    if (!pretentAssData.checkboxShow) {
                        checkedArray.push(true);
                    } else {
                        checkedArray.push(checkedAll);
                    }
                })
                self.setState({
                    assData: pretentAssData.assData,
                    childAssData, checkedArray, checkedAll
                })
            } else if (pretentAssData.assid) {
                checkedArray = [];
                let assidParam = {
                    pk_accasoa: pretentAssData.pk_accasoa,
                    date: pretentAssData.prepareddate,
                    assid: pretentAssData.assid,
                    notVersion:true //不进行版本处理
                }

                commonApi.queryAssTypeAndValue(assidParam, (data) => {
                    if (data && data.length > 0) {
                        data.map((item, index) => {
                            if (item.pk_Checkvalue && item.pk_Checkvalue == "~") {
                                item.pk_Checkvalue = null;
                            }
                            item.key = index;
                            checkedArray.push(checkedAll);
                            item.m_classid = item.classid;
                            item.pk_Checktype = item.pk_accassitem;
                        })
                    }
                    childAssData.assData = data;
                    self.setState({
                        assData: data,
                        childAssData, checkedAll, checkedArray
                    })
                })
            } else {
                assData = [];
                checkedArray = [];
                //请求辅助核算数据
                let queryData = {
                    pk_accasoa: pretentAssData.pk_accasoa,
                    prepareddate: pretentAssData.prepareddate,
                };

                /* 是否包含下级科目辅助核算，默认不包含 */
                if (nextProp.hasOwnProperty('includeSubAss') && nextProp.includeSubAss) {
                    queryData.includeSub = nextProp.includeSubAss;
                }

                commonApi.queryAssItem(queryData, (data) => {
                    if (data && data.length > 0) {
                        data.map((item, index) => {
                            item.key = index;
                            checkedArray.push(checkedAll);
                            let obj = {
                                key: index,
                                "checktypecode": item.code,
                                "checktypename": item.name,
                                "pk_Checktype": item.pk_accassitem,
                                "refCode": item.refCode ? item.refCode : item.code,
                                "refnodename": item.refnodename,
                                "pk_accassitem": item.pk_accassitem,
                                "m_classid": item.classid,
                                "classid": item.classid,
                                "pk_defdoclist": item.classid,
                                "pk_accountingbook": childAssData.pk_accountingbook,
                                inputlength: item.inputlength ? item.inputlength : '',
                                digits: item.digits ? item.digits : '0'

                            }
                            assData.push(obj);
                        })

                    }
                    childAssData.assData = assData;
                    self.setState({
                        assData, childAssData, checkedAll, checkedArray
                    })
                });
            }
        }
    }


    //表格操作根据key寻找所对应行
    findByKey(key, rows) {
        let rt = null;
        let self = this;
        rows.forEach(function (v, i, a) {
            if (v.key == key) {
                rt = v;
            }
        });
        return rt;
    }

    close() {
        this.props.handleClose();
    }
    //确定 过滤勾选的数据
    confirm = () => {
        let self = this;
        let { SelectedAssData, checkedArray, listItem, assData, childAssData } = self.state;
        SelectedAssData = [];//清空
        let url = '/nccloud/gl/voucher/queryAssId.do';
        for (var i = 0; i < checkedArray.length; i++) {
            if (checkedArray[i] == true) {
                SelectedAssData.push(assData[i]);
            }
        }
        let sendData = {};
        let assid = '', assname = '';
        if (SelectedAssData.length > 0) {
            let parm = { "ass": assData, "pk_accountingbook": childAssData.pk_accountingbook };
            commonApi.queryAssId(parm, (data) => {
                if (data) {
                    assid = data.assid;
                    assname = data.assname ? data.assname : '';
                    sendData = {
                        data: SelectedAssData,
                        assid: assid,
                        assname: assname
                    }
                    self.props.onConfirm(sendData);
                }
            });
        } else {
            sendData = {
                data: SelectedAssData,
                assid: assid,
                assname: assname
            }
            self.props.onConfirm(sendData);
        }
    }

    //全选
    onAllCheckChange = () => {
        let self = this;
        let checkedArray = [];
        let selIds = [];
        for (var i = 0; i < self.state.checkedArray.length; i++) {
            checkedArray[i] = !self.state.checkedAll;
        }
        self.setState({
            checkedAll: !self.state.checkedAll,
            checkedArray: checkedArray,
        });
    };
    //单选
    onCheckboxChange = (text, record, index) => {
        let self = this;
        let allFlag = false;
        let checkedArray = self.state.checkedArray.concat();
        checkedArray[index] = !self.state.checkedArray[index];
        for (var i = 0; i < self.state.checkedArray.length; i++) {
            if (!checkedArray[i]) {
                allFlag = false;
                break;
            } else {
                allFlag = true;
            }
        }
        self.setState({
            checkedAll: allFlag,
            checkedArray: checkedArray,
        });
    };

    renderColumnsMultiSelect(columns) {
        const { checkedArray } = this.state;
        const { multiSelect } = this.props;
        let indeterminate_bool = false;
        if (multiSelect && multiSelect.type === "checkbox") {
            let i = checkedArray.length;
            while (i--) {
                if (checkedArray[i]) {
                    indeterminate_bool = true;
                    break;
                }
            }
            let defaultColumns = [
                {
                    title: (
                        <span fieldid="firstcol">
                        <Checkbox
                            className="table-checkbox"
                            checked={this.state.checkedAll}
                            indeterminate={indeterminate_bool && !this.state.checkedAll}
                            onChange={this.onAllCheckChange}
                        />
                        </span>
                    ),
                    key: "checkbox",
                    attrcode: 'checkbox',
                    dataIndex: "checkbox",
                    width: "60px",
                    render: (text, record, index) => {
                        return (
                            <span fieldid="firstcol">
                            <Checkbox
                                className="table-checkbox"
                                checked={this.state.checkedArray[index]}
                                onChange={this.onCheckboxChange.bind(this, text, record, index)}
                            />
                            </span>
                        );
                    }
                }
            ];
            columns = defaultColumns.concat(columns);
        }
        return columns;
    }

    render() {
        let { showOrHide, pretentAssData } = this.props;
        let { loadData, assData } = this.state;
        let columnsldad;
        let { json } = this.state
        let showDisableData = true;
        if (this.props.hasOwnProperty('showDisableData')) {
            if (this.props.showDisableData != 'show') {
                showDisableData = false;
            }
        }
        let columns10=[
            {
              title: (<span fieldid='checktypecode'>{this.state.json['publiccomponents-000001']}</span>),/* 国际化处理： 核算类型编码*/
              dataIndex: "checktypecode",
              key: "checktypecode",
              width: '100',
              render: (text, record, index) => {
				return <span fieldid='checktypecode'>{record.checktypecode}</span>;
			    }
            },
            {
                title: (<span fieldid='checktypename'>{this.state.json['publiccomponents-000002']}</span>),/* 国际化处理： 核算类型名称*/
                dataIndex: "checktypename",
                key: "checktypename",
                width: '200',
                render: (text, record, index) => {
                  return <span fieldid='checktypename'>{record.checktypename}</span>;
                  }
              },
            {
              title: (<span fieldid='checkvaluename'>{this.state.json['publiccomponents-000003']}</span>),/* 国际化处理： 核算内容*/
              dataIndex: "checkvaluename",
              key: "checkvaluename",
              width: '200',
                render: (text, record, index) => {
                    return (drawinAss(this,text, record, index,showDisableData,json))
                }
            }
        ];
        if (pretentAssData.checkboxShow) {//复选框显示true
            columnsldad = this.renderColumnsMultiSelect(columns10);
        } else {
            columnsldad = columns10;
        }

        const emptyFunc = () => <span>{this.state.json['publiccomponents-000007']}！</span>/* 国际化处理： 这里没有数据*/
        return (
            <div className="nc_group">
                <Modal
                    fieldid='assid'
                    show={showOrHide}
                    backdrop='static'
                    onHide={this.close}
                    animation={true}
                    className="AssidModalaa"
                    zIndex={250}
                >
                    <Modal.Header closeButton>
                        <Modal.Title>{this.state.json['publiccomponents-000008']}</Modal.Title>{/* 国际化处理： 辅助核算*/}
                    </Modal.Header >
                    <Modal.Body style={modalStyle}>
                        <Table
                            columns={columnsldad}
                            data={assData}
                            emptyText={emptyFunc}
                        />
                    </Modal.Body>
                    <Modal.Footer>
                        <Button fieldid='confirm' colors="primary" onClick={this.confirm}> {this.state.json['publiccomponents-000009']} </Button>{/* 国际化处理： 确定*/}
                        <Button fieldid='cancel' onClick={this.close}> {this.state.json['publiccomponents-000010']} </Button>{/* 国际化处理： 取消*/}
                    </Modal.Footer>
                </Modal>
            </div>
        )
    }
}
AssModal.defaultProps = defaultProps12;